package com.atomikos.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@MapperScan(basePackages = "com.wenqy.mapper.three", sqlSessionTemplateRef = "threeSqlSessionTemplate")
public class ThreeDbConfig {
    @Bean(name = "threeDataSource")
    public DataSource twoDataSource(TwoDbProperties twoDbProperties) throws SQLException {
        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
        mysqlXaDataSource.setUrl(twoDbProperties.getUrl());
        mysqlXaDataSource.setPassword(twoDbProperties.getPassword());
        mysqlXaDataSource.setUser(twoDbProperties.getUsername());
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setUniqueResourceName("twoDataSource");
        xaDataSource.setMinPoolSize(twoDbProperties.getMinPoolSize());
        xaDataSource.setMaxPoolSize(twoDbProperties.getMaxPoolSize());
        xaDataSource.setMaxLifetime(twoDbProperties.getMaxLifetime());
        xaDataSource.setBorrowConnectionTimeout(twoDbProperties.getBorrowConnectionTimeout());
        xaDataSource.setLoginTimeout(twoDbProperties.getLoginTimeout());
        xaDataSource.setMaintenanceInterval(twoDbProperties.getMaintenanceInterval());
        xaDataSource.setMaxIdleTime(twoDbProperties.getMaxIdleTime());
        xaDataSource.setTestQuery(twoDbProperties.getTestQuery());
        return xaDataSource;
    }
    @Bean(name = "threeSqlSessionFactory")
    public SqlSessionFactory twoSqlSessionFactory(@Qualifier("threeDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/config/two/*.xml"));
        return bean.getObject();
    }
    @Bean(name = "threeSqlSessionTemplate")
    public SqlSessionTemplate twoSqlSessionTemplate(
            @Qualifier("threeSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}